/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.fastagenerator.fastagrabber.consoleformatter;

import java.io.Console;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.DuplicateFormatFlagsException;

/**
 *
 * @author Kenneth
 */
public class Percent {

    private Console console;
    private BigDecimal percent = BigDecimal.ZERO;
    private static final BigDecimal maxPercent = new BigDecimal(100);
    private int maxValue = 100;
    private int totalIncrement = 0;
    private String prefix;
    private final String regex = " 100% ";
    private String suffix;

    public Percent(int maxValue) {
        this.maxValue = maxValue;
        console = System.console();
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    public void setSurroundMessage(String prefix, String suffix) {
        this.prefix = prefix;
        this.suffix = suffix;
    }

    public void setPercent(int percent) {
        this.percent = new BigDecimal(percent);
    }

    public void increasePercent(int increment) {
        percent = calculatePercent(increment);
        if (percent.compareTo(maxPercent.subtract(BigDecimal.ONE)) == 1) {
            percent = maxPercent;
        }
        if (percent.compareTo(maxPercent) != 1) {
            try {
                Thread.sleep(150);
                String printString;
                if (percent.toString().contains(".")) {
                    printString = prefix + " " + percent.toString().substring(0, percent.toString().indexOf(".")) + "% " + suffix;
                } else {
                    printString = prefix + " " + percent + "% " + suffix;
                }
                clearPercent(printString);
                System.out.print(printString);
            } catch (DuplicateFormatFlagsException e) {
                e.printStackTrace();
                System.out.println(e.getFlags());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println();
        }
    }

    private BigDecimal calculatePercent(int increment) {
        totalIncrement += increment;
        percent = new BigDecimal(totalIncrement).multiply(new BigDecimal(100).divide(new BigDecimal(maxValue), 2, RoundingMode.HALF_UP));
        return percent;
    }

    private void clearPercent(String printString) {
        if (console != null) {
            int clearingSize = printString.length();
            for (int i = 0; i <= clearingSize; i++) {
                console.printf("\u0008");
            }
        }
    }
}